import csv
from seleniumbase import SB

# Configuration file
from config import *

# Defines file for parsing (DO NOT CHANGE)
from defines import *

# For perfomance purposes
from time import time

# For filename format
from datetime import datetime
import os
filename = 'data/{}_{}_{}'.format(datetime.now().year, datetime.now().month, datetime.now().day)

# Switching to cookies iframe and accepting it
def check_cookies() -> None:
    # TODO: Make cookies check
    pass

def make_dict_from_str(string: str) -> dict:
    lines = string.splitlines()
    result = dict()

    for i in range(0, len(lines), 2):
        if i + 1 < len(lines):
            key = lines[i]
            value = lines[i + 1]
            result[key] = value
    
    return result

def write_to_file(f_data: dict, filename: str, savetype: str = 'txt') -> bool:
    os.makedirs(os.path.dirname(filename), exist_ok=True)

    if savetype == 'txt':
        with open('{}'.format(filename), 'w') as f:
            for key, value in f_data.items():
                f.write('{} {}\n'.format(key, value))

    elif savetype == 'csv':
        with open('{}'.format(filename), 'w') as f:
            fieldnames = ['Currency', 'BFIX Rate']
            writer = csv.DictWriter(f, fieldnames=fieldnames)
            writer.writeheader()

            for key, value in f_data.items():
                writer.writerow({'Currency': key, 'BFIX Rate': value})

    else:
        return False
    
    return True

# Raw data acquisition without configuration
def parse_no_preconf(savetype: str = 'txt') -> bool:
    start = time()

    with SB(uc=True, save_screenshot=True, headless=True) as sb:
        sb.driver.uc_open_with_reconnect(BLOOMBERG_URL, RECON_TIMEOUT)

        check_cookies()
        
        fx_pairs = sb.driver.get_text(DATA_TABLE_BODY_XPATH)
        f_data = make_dict_from_str(fx_pairs)

        fn = filename + '.{}'.format(savetype)
        if not write_to_file(f_data, filename, savetype):
            print('Not supported file extension')
            return False
        
        end = time()

        print('Parsed successfully in {} sec! Check data in {}'.format(round(end - start), fn))
        return True
    
# Raw data acquisition with configuration based on exchange picking
def parse_exchange_preconf(savetype: str = 'txt', exchange: str = 'Beijing') -> bool:
    if exchange not in EXCHANGES_DICT:
        print('Not supported exchange, see defines.py : EXCHANGES_LIST for available exchanges list')
        return False, -1
    
    start = time()

    with SB(uc=True, save_screenshot=True, headless=True) as sb:
        sb.driver.uc_open_with_reconnect(BLOOMBERG_URL, RECON_TIMEOUT)

        check_cookies()

        # FIXME: This is a weird solution but it works
        sb.slow_scroll_to('select')
        sb.driver.click('select')
        sb.driver.click('//option[@value="{}"]'.format(EXCHANGES_DICT[exchange]))
        sb.driver.sleep(SELECTOR_TIMEOUT)
        
        fx_pairs = sb.driver.get_text(DATA_TABLE_BODY_XPATH)
        f_data = make_dict_from_str(fx_pairs)

        fn = filename + '_{}'.format(exchange.lower()) + '.{}'.format(savetype)
        if not write_to_file(f_data, fn, savetype):
            print('Not supported file extension')
            return False
        
        end = time()

        print('Parsed successfully in {} sec! Check data in {}'.format(round(end - start), fn))
        return True